/*
 * Filename:    IntegrityBusinessServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月29日
 */
package com.paic.mhis.hcpms.trust.biz.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityBusinessService;
import com.paic.mhis.hcpms.trust.common.TrustConstants;
import com.paic.mhis.hcpms.trust.dto.BlackExcelDataSourceDTO;
import com.paic.mhis.hcpms.trust.dto.BlackParamterCondtion;
import com.paic.mhis.hcpms.trust.dto.BlackPatientBaseInfoDTO;
import com.paic.mhis.hcpms.trust.dto.BlackResultAliasDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityAttentionIllegalDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityAttentionLevelDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityBlackDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityBlackOpinionDTO;
import com.paic.mhis.hcpms.trust.intergration.dao.IntegrityBlackDao;
import com.paic.mhis.hcpms.trust.util.ExportBlackComboxExcel;
import com.paic.pafa.exceptions.BusinessException;

@Component("integrityBusinessServiceImpl")
public class IntegrityBusinessServiceImpl implements IntegrityBusinessService {

	public static Log log = LogFactory.getLog(IntegrityBusinessServiceImpl.class);

	@Autowired
	private IntegrityBlackDao integrityBlackDao;

	@Transactional
	public void saveIntegrityBean(IntegrityBlackDTO bean) {

		this.integrityBlackDao.insertIntegrityBlackPerson(bean);

	}

	public List<IntegrityBlackDTO> queryIntegrityBlackDTO(BlackParamterCondtion paramter) {

		return this.integrityBlackDao.queryIntegrityBlackPerson(paramter);
	}

	@Override
	public long queryIntegrityBlackDTOCount(BlackParamterCondtion paramter) {
		return this.integrityBlackDao.queryIntegrityBlackCount(paramter);

	}

	@Transactional
	@Override
	public void updateIntegrityBlackDTO(IntegrityBlackDTO bean) {
		this.integrityBlackDao.updateIntegrityBlackPerson(bean);
	}

	@Override
	public IntegrityBlackDTO getIntegrityBlackDTOBySociationNum(String sociationNum) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sociationNum", sociationNum);

		IntegrityBlackDTO bean = this.integrityBlackDao.getIntegrityBlackDTOBySocaitionNum(map);
		return bean;
	}

	@Override
	public IntegrityBlackDTO queryattentionMidIdCilck(String sociationNum) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mid", sociationNum);

		IntegrityBlackDTO bean = this.integrityBlackDao.queryattentionMidIdCilck(map);
		return bean;
	}

	@Override
	public List<IntegrityBlackDTO> queryattentionMidIdCilckList(String sociationNum) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mid", sociationNum);

		return integrityBlackDao.queryattentionMidIdCilckList(map);
	}

	@Override
	public List<IntegrityBlackDTO> loadAllIntegrityBlackDTO(BlackParamterCondtion parameter) {
		return this.integrityBlackDao.loadAllIntegrityBlackPerson(parameter);
	}

	public long queryBlackPaientBaseInfoCount(BlackParamterCondtion bean) {

		return this.integrityBlackDao.queryBlackPaientBaseInfoCount(bean);
	}

	public List<BlackPatientBaseInfoDTO> queryBlackPatientBaseInfoDTO(BlackParamterCondtion bean) {

		return this.integrityBlackDao.queryBlackPatientBaseInfoDTO(bean);
	}

	@Transactional
	@Override
	public void processIntegrityBeanList(List<IntegrityBlackDTO> list) {
		String currentSeq = integrityBlackDao.querySeqUploadNextval();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				IntegrityBlackDTO bean = list.get(i);
				// 根据 关注级别 查出 关注级别中间表id 赋值给bean 对象在进行添加
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("mid", bean.getAttentionLevel());
				List<IntegrityBlackDTO> bean2 = integrityBlackDao.queryattentionMidIdCilckList(map);
				for (IntegrityBlackDTO dto : bean2) {
					if (dto.getIllegal().equals(bean.getIllegal())) {
						bean.setAttentionMidId(dto.getAttentionMidId());
					}
				}
				bean.setProcessState(TrustConstants.process_state_01);
				bean.setSwiftNumber(DateFormatUtils.format(new Date(), "yyMMdd").concat(currentSeq)
						.concat(String.format("%04d", i + 1)));

				this.integrityBlackDao.insertIntegrityBlackPerson(bean);
			}

		}
	}

	@Override
	public boolean processCheckBlackExist(String personCard) {

		BlackParamterCondtion parameter = new BlackParamterCondtion();
		parameter.setPersonCard(personCard);
		boolean flag = this.integrityBlackDao.checkBlackPaientBaseInfo(parameter);

		return flag;

	}

	@Override
	public List<Map<String, Object>> queryAttentionLevelInfo(String type, String attentionLevelId) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		// 查询关注级别
		if (TrustConstants.type_01.equals(type)) {
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("attentionLevelId", attentionLevelId);
			List<IntegrityAttentionLevelDTO> currentList = this.integrityBlackDao.queryAllAttentionLevels(parameterMap);

			if (currentList != null && currentList.size() > 0) {
				for (IntegrityAttentionLevelDTO bean : currentList) {
					String attentionMidId = bean.getAttentionMidId();
					String attentionLevel = bean.getAttentionLevel();
					String attentionTime = bean.getAttentionTime();

					Map<String, Object> currentMap = new HashMap<String, Object>();
					currentMap.put("attentionMidId", attentionMidId);
					currentMap.put("attentionLevel", attentionLevel);
					currentMap.put("attentionTime", attentionTime);

					list.add(currentMap);
				}
			}

		} else if (TrustConstants.type_02.equals(type)) { // 查询违规情节
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			List<IntegrityAttentionIllegalDTO> illegalList = this.integrityBlackDao.queryAllIllegalInfo(parameterMap);

			if (illegalList != null && illegalList.size() > 0) {

				for (IntegrityAttentionIllegalDTO bean : illegalList) {

					String id = bean.getId();
					String illegal = bean.getIllegal();

					Map<String, Object> currentMap = new HashMap<String, Object>();
					currentMap.put("attentionMidId", bean.getAttentionMidId());
					currentMap.put("illegal", illegal);
					currentMap.put("attentionLevelId", bean.getAttentionLevelId());
					list.add(currentMap);
				}

			}

		}
		return list;
	}

	@Transactional
	@Override
	public Map<String, Object> cancelBuinsessProcess(String blackId) {

		Map<String, Object> map = new HashMap<String, Object>();
		IntegrityBlackDTO paramterBean = new IntegrityBlackDTO();
		paramterBean.setId(blackId);

		IntegrityBlackDTO bean = this.integrityBlackDao.getIntegrityBlackDTOById(blackId);

		if (bean != null) {
			String processState = bean.getProcessState();
			if (TrustConstants.process_state_02.equals(processState)) { // 已审核
				map.put("flag", false);
				map.put("msg", TrustConstants.record_passed);
			} else {
				paramterBean.setProcessState(TrustConstants.process_state_03);
				this.integrityBlackDao.updateIntegrityBlackPerson(paramterBean);
				map.put("flag", true);
				map.put("msg", TrustConstants.OPERATE_SUCCESS);
			}
		} else {
			map.put("flag", false);
			map.put("msg", TrustConstants.record_undefined);
		}

		return map;
	}

	/**
	 * 处理参保人黑名单审核意见信息
	 */
	@Transactional
	@Override
	public Map<String, Object> processBlackAuditInfo(List<String> idsList, UserDetails user, String opinion,
			String opinionDesc) {
		String userName = user.getUsername();
		Map<String, Object> map = new HashMap<String, Object>();
		if (idsList != null && idsList.size() > 0) {
			for (String id : idsList) {
				IntegrityBlackDTO bean = new IntegrityBlackDTO();
				bean.setId(id);
				bean.setUpdateDate(new Date());
				if (TrustConstants.opinion_0.equals(opinion)) {
					bean.setProcessState(TrustConstants.process_state_04);
				} else if (TrustConstants.opinion_1.equals(opinion)) {
					this.processExpiteDate(id, bean);
					bean.setProcessState(TrustConstants.process_state_02);
				}
				bean.setOpertionUser(userName);
				bean.setUpdateDate(new Date());
				this.integrityBlackDao.updateIntegrityBlackPerson(bean);

				IntegrityBlackOpinionDTO opinionBean = this.integrityBlackDao.queryAuditOpinion(id);
				if (null != opinionBean) {
					opinionBean.setOpinion(opinion);
					opinionBean.setOpinionDesc(opinionDesc);
					opinionBean.setOpertionUser(user.getUsername());
					this.integrityBlackDao.updateAuditOpinion(opinionBean);
				} else {
					IntegrityBlackOpinionDTO saveOpinion = new IntegrityBlackOpinionDTO();
					saveOpinion.setBlackId(id);
					saveOpinion.setOpinion(opinion);
					saveOpinion.setOpinionDesc(opinionDesc);
					saveOpinion.setOpertionUser(user.getUsername());
					this.integrityBlackDao.insertIntegrityBlackOpinionBean(saveOpinion);
				}

			}
			map.put("flag", true);
			map.put("msg", TrustConstants.OPERATE_SUCCESS);
		} else {
			map.put("flag", false);
			map.put("msg", TrustConstants.record_undefined);
		}
		return map;
	}

	/**
	 * 如何审核的日期大于有效期的开始日期,则将审核日期更新为当前的有效期开始日期，同时结束日期也相应的变化
	 * 
	 * @param blackId
	 */
	private void processExpiteDate(String blackId, IntegrityBlackDTO paramterBean) {

		IntegrityBlackDTO bean = this.getIntegrityBlackDTOById(blackId);

		Date submitDate = bean.getStartDate();

		// 审核日期
		Date auditDate = new Date();

		if (auditDate.after(submitDate)) { // 审核日期大于了录入提交的有效开始日期

			Calendar nowDate = Calendar.getInstance();
			Calendar oldDate = Calendar.getInstance();
			nowDate.setTime(auditDate);// 设置为当前系统时间
			oldDate.setTime(submitDate);

			long timeNow = nowDate.getTimeInMillis();
			long timeOld = oldDate.getTimeInMillis();
			long day = (timeNow - timeOld) / (1000 * 60 * 60 * 24);// 化为天

			Date endDate = bean.getEndDate();

			Calendar endDateCalendar = Calendar.getInstance();
			endDateCalendar.setTime(endDate);

			int endYear = endDateCalendar.get(Calendar.YEAR);

			if (endYear != 9999) { //

				endDateCalendar.add(Calendar.DAY_OF_MONTH, (int) day);

				Date currentEndDate = endDateCalendar.getTime();

				paramterBean.setEndDate(currentEndDate);
			}

			paramterBean.setStartDate(auditDate);

		}

	}

	@Override
	public IntegrityBlackDTO getIntegrityBlackDTOById(String id) {
		IntegrityBlackDTO bean = this.integrityBlackDao.getIntegrityBlackDTOById(id);
		return bean;
	}

	@Override
	public long querySameParamPerson(String name, String cardNo, String cardType) {
		return integrityBlackDao.querySameParamPerson(name, cardNo, cardType);
	}

	@Override
	public void queryBlackWithExportExcel(String filePath, String fileNameResource, String fileNameTarget)
			throws BusinessException {
		System.out.println(filePath);
		log.info("开始执行 queryBlackWithExportExcel ..............");
		List<BlackResultAliasDTO> blis = integrityBlackDao.queryBlackResultAlias();
		Map<String, Object> tmp = new HashMap<String, Object>();
		for (BlackResultAliasDTO ba : blis) {
			String alias =  "级别"+ba.getLevelAlias()+"\\关注"+ba.getAttentionTime() ;
			if (tmp.get(alias) != null) {
				List<String> tlis = (List<String>) tmp.get(alias);
				tlis.add(ba.getDetailResult());
				tmp.put(alias, tlis);
			} else {
				List<String> tlis = new ArrayList<String>();
				tlis.add(ba.getDetailResult());
				tmp.put(alias, tlis);
			}
		}

		List<BlackExcelDataSourceDTO> data = new ArrayList<BlackExcelDataSourceDTO>();

		for (Entry<String, Object> entry : tmp.entrySet()) {
			BlackExcelDataSourceDTO ttd = new BlackExcelDataSourceDTO();
			ttd.setDetailList((List<String>) entry.getValue());
			ttd.setLevelAlias(entry.getKey().toString());
			data.add(ttd);
		}

		log.info("开始  ExportExcel .............._2_");
		new ExportBlackComboxExcel(filePath, fileNameResource, fileNameTarget, data);
		log.info("结束  ExportExcel .............._3_");

		log.info("结束执行 queryBlackWithExportExcel .............._4_");
	}

	private static Map<String, String> tmp = new HashMap<String, String>();

	@Override
	public List<Map<String, Object>> getCurrentSwiftNumber() {
		
		return integrityBlackDao.getCurrentSwiftNumber();
	}
	@Override
	public void updateCurrentSwiftNumber(Map<String, Object> paraMap){
		
		integrityBlackDao.updateCurrentSwiftNumber(paraMap);
	}
}
